﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Net.Mime;

namespace EnhancedSolutions
{
    class Zipper
    {
        private string path;
        private ExtractedSolutionList solList;

        public Zipper(string _path, ExtractedSolutionList _solList)
        {
            this.path = _path;
            this.solList = _solList;
        }

        /// <summary>
        /// Creates the zip file.
        /// </summary>
        /// <returns>True if the zip was created, false if not.</returns>
        public bool CreateZipFile()
        {
            string zipFileName = this.path;

            using (Package package = ZipPackage.Open(zipFileName, FileMode.Create))
            {
                foreach (ExtractedSolution solution in this.solList)
                {
                    string destFilename = ".\\" + Path.GetFileName(solution.Targetpath);
                    Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));

                    PackagePart packagePart = package.CreatePart(uri, MediaTypeNames.Application.Octet, CompressionOption.NotCompressed);
                    using (FileStream fileStream = new FileStream(solution.Targetpath, FileMode.Open, FileAccess.Read))
                    {
                        CopyStream(fileStream, packagePart.GetStream());
                    }
                }
            }

            if (File.Exists(this.path))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Copies the stream.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="target">The target.</param>
        private void CopyStream(Stream source, Stream target)
        {
            const int bufSize = 16384;
            byte[] buf = new byte[bufSize];
            int bytesRead = 0;
            while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
                target.Write(buf, 0, bytesRead);
        }
    }
}
